import { ref, reactive, watch } from "vue";

export default function loadList(page, getListFn = () => {}) {
  const dataList = ref([]);
  const isMore = ref(false);
  const isFinished = ref(false);

  //  页面筛选
  const curPage = ref(page);

  //  加载更多数据
  const handleLoad = async () => {
    isMore.value = true;
    //   发送网络请求 请求数据
    dataList.value = dataList.value.concat((await getListFn(curPage.value)) || []);
    isMore.value = false;
    curPage.value.currentPage++;
  };

  //  下拉刷新
  const handleRefresh = async (callback = () => {}) => {
    isFinished.value = false;
    curPage.value.currentPage = 1;
    //  清空数据
    dataList.value = [];
    isMore.value = true;
    dataList.value = (await getListFn(curPage.value) || []);
    isMore.value = false;
    callback();
  };

  //  设置 page 参数
  const setPageOption = async (options) => {
    curPage.value = Object.assign({}, curPage.value, options);
    await handleRefresh();
  }

  //  数据全部加载完成
  const setFinished = () => {
    isFinished.value = true;
  };

  return {
    dataList,
    isMore,
    isFinished,
    handleLoad,
    handleRefresh,
    setPageOption,
    setFinished,
  };
}
